<template>
  <div class="requirement-associations-tab">
    <el-tabs v-model="activeSubTab" type="border-card" class="association-sub-tabs">
      <!-- 关联任务子页签 -->
      <el-tab-pane label="关联任务" name="tasks">
        <div class="sub-tab-content">
          <div class="tab-header">
            <div class="header-info">
              <span class="item-count">关联任务（{{ relatedTasks.length }}）</span>
            </div>
            <div class="header-actions">
              <el-button
                type="primary"
                size="small"
                @click="handleAddTask"
              >
                <el-icon><Plus /></el-icon>
                添加任务
              </el-button>
            </div>
          </div>

          <div v-loading="tasksLoading" class="items-list">
            <el-table
              v-if="relatedTasks.length > 0"
              :data="relatedTasks"
              size="default"
              border
              stripe
              style="width: 100%"
            >
              <el-table-column prop="title" label="任务标题" min-width="200" show-overflow-tooltip>
                <template #default="{ row }">
                  <el-link
                    type="primary"
                    @click="handleViewTask(row.id)"
                    :underline="false"
                  >
                    {{ row.title }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag
                    :type="getTaskStatusType(row.status)"
                    size="small"
                  >
                    {{ getTaskStatusName(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="priority" label="优先级" width="90">
                <template #default="{ row }">
                  <el-tag
                    :type="getTaskPriorityType(row.priority)"
                    size="small"
                  >
                    {{ getTaskPriorityName(row.priority) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="负责人" width="150" show-overflow-tooltip>
                <template #default="{ row }">
                  <UserDisplay
                    :user-id="row.assignee_id"
                    :user-name="row.assignee_name"
                    :show-avatar="true"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="due_date" label="截止日期" width="110">
                <template #default="{ row }">
                  {{ formatDate(row.due_date) || '—' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ row }">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="handleViewTask(row.id)"
                  >
                    查看
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    size="small"
                    @click="handleRemoveTask(row)"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无关联任务" :image-size="80" />
          </div>
        </div>
      </el-tab-pane>

      <!-- 关联缺陷子页签 -->
      <el-tab-pane label="关联缺陷" name="defects">
        <div class="sub-tab-content">
          <div class="tab-header">
            <div class="header-info">
              <span class="item-count">关联缺陷（{{ relatedDefects.length }}）</span>
            </div>
            <div class="header-actions">
              <el-button
                type="primary"
                size="small"
                @click="handleAddDefect"
              >
                <el-icon><Plus /></el-icon>
                添加缺陷
              </el-button>
            </div>
          </div>

          <div v-loading="defectsLoading" class="items-list">
            <el-table
              v-if="relatedDefects.length > 0"
              :data="relatedDefects"
              size="default"
              border
              stripe
              style="width: 100%"
            >
              <el-table-column prop="title" label="缺陷标题" min-width="200" show-overflow-tooltip>
                <template #default="{ row }">
                  <el-link
                    type="primary"
                    @click="handleViewDefect(row.id)"
                    :underline="false"
                  >
                    {{ row.title }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag
                    :type="getDefectStatusType(row.status)"
                    size="small"
                  >
                    {{ getDefectStatusName(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="severity" label="严重程度" width="100">
                <template #default="{ row }">
                  <el-tag
                    :type="getDefectSeverityType(row.severity)"
                    size="small"
                  >
                    {{ getDefectSeverityName(row.severity) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="priority" label="优先级" width="90">
                <template #default="{ row }">
                  <el-tag
                    :type="getDefectPriorityType(row.priority)"
                    size="small"
                  >
                    {{ getDefectPriorityName(row.priority) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="负责人" width="150" show-overflow-tooltip>
                <template #default="{ row }">
                  <UserDisplay
                    :user-id="row.assignee_id"
                    :user-name="row.assignee_name"
                    :show-avatar="true"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="报告人" width="150" show-overflow-tooltip>
                <template #default="{ row }">
                  <UserDisplay
                    :user-id="row.reporter_id"
                    :user-name="row.reporter_name"
                    :show-avatar="true"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ row }">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="handleViewDefect(row.id)"
                  >
                    查看
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    size="small"
                    @click="handleRemoveDefect(row)"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无关联缺陷" :image-size="80" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 任务选择对话框 -->
    <TaskSelectorDialog
      v-model="taskSelectorVisible"
      :project-id="projectId"
      :version-ids="versionIds"
      :exclude-task-ids="relatedTasks.map(t => t.id)"
      @confirm="handleTaskSelected"
    />

    <!-- 缺陷选择对话框 -->
    <DefectSelectorDialog
      v-model="defectSelectorVisible"
      :project-id="projectId"
      :version-ids="versionIds"
      :exclude-defect-ids="relatedDefects.map(d => d.id)"
      @confirm="handleDefectSelected"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { getTaskList } from '@/api/task'
import { getTask } from '@/api/tasks'
import type { Task } from '@/api/task'
import { getDefectsByRequirementId, batchUpdateDefectsRequirement, getDefectById } from '@/api/defect'
import type { Defect } from '@/api/defect'
import { formatDate } from '@/utils/date'
import { useTaskStates } from '@/composables/useTaskStates'
import { useDefectStates } from '@/composables/useDefectStates'
import { useDefectOptions } from '@/composables/useDefectOptions'
import { versionAPI, RelationType } from '@/api/version'
import TaskSelectorDialog from '@/components/version/TaskSelectorDialog.vue'
import DefectSelectorDialog from '@/components/version/DefectSelectorDialog.vue'
import UserDisplay from '@/components/ui/UserDisplay.vue'

interface Props {
  requirementId: string
  versionIds?: string[]
  projectId?: string
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'task-updated'): void
  (e: 'defect-updated'): void
  (e: 'create-task'): void
  (e: 'update-requirement', data: { project_id?: string; version_ids?: string[] }): void
}>()

const router = useRouter()
const activeSubTab = ref('tasks')
const tasksLoading = ref(false)
const defectsLoading = ref(false)
const relatedTasks = ref<Task[]>([])
const relatedDefects = ref<Defect[]>([])
const taskSelectorVisible = ref(false)
const defectSelectorVisible = ref(false)

const { loadStates: loadTaskStates, getStateName: getTaskStateName } = useTaskStates()
const { getStateName: getDefectStateName, getStateColor: getDefectStateColor, loadStates: loadDefectStates } = useDefectStates()
const { getSeverityName: getSeverityNameFromOptions, getPriorityName: getPriorityNameFromOptions, loadOptions: loadDefectOptions } = useDefectOptions()

// 加载关联任务
const loadRelatedTasks = async () => {
  if (!props.requirementId) {
    relatedTasks.value = []
    return
  }

  try {
    tasksLoading.value = true
    await loadTaskStates()
    
    const response = await getTaskList({
      requirement_id: props.requirementId,
      size: 100
    })
    
    relatedTasks.value = response.items || []
  } catch (error) {
    console.error('加载关联任务失败:', error)
    ElMessage.error('加载关联任务失败')
    relatedTasks.value = []
  } finally {
    tasksLoading.value = false
  }
}

// 加载关联缺陷
const loadRelatedDefects = async () => {
  if (!props.requirementId) {
    relatedDefects.value = []
    return
  }

  defectsLoading.value = true
  try {
    const response: any = await getDefectsByRequirementId(props.requirementId)
    let defects: Defect[] = []
    
    if (response && response.data) {
      const data = response.data
      if (Array.isArray(data)) {
        defects = data
      } else if (data.success && data.data) {
        if (Array.isArray(data.data)) {
          defects = data.data
        } else if (data.data.items && Array.isArray(data.data.items)) {
          defects = data.data.items
        }
      } else if (data.items && Array.isArray(data.items)) {
        defects = data.items
      } else if (data.data && Array.isArray(data.data)) {
        defects = data.data
      }
    } else if (Array.isArray(response)) {
      defects = response
    }
    
    relatedDefects.value = defects
  } catch (error) {
    console.error('获取关联缺陷失败:', error)
    ElMessage.error('获取关联缺陷失败')
    relatedDefects.value = []
  } finally {
    defectsLoading.value = false
  }
}

// 添加任务
const handleAddTask = () => {
  taskSelectorVisible.value = true
}

// 验证任务是否符合关联条件（允许项目/版本为空，但如果存在则需要一致）
const validateTaskForAssociation = async (task: Task): Promise<{ 
  valid: boolean
  message?: string
  needsUpdateRequirement?: boolean
  updateData?: { project_id?: string; version_ids?: string[] }
}> => {
  const updateData: { project_id?: string; version_ids?: string[] } = {}
  let needsUpdate = false
  let message = ''
  
  // 验证项目ID是否一致（只有当任务有项目ID且需求也有项目ID时才验证）
  if (task.project_id) {
    if (props.projectId && task.project_id !== props.projectId) {
      // 不一致，提示并询问是否更新需求的项目
      message = `任务"${task.title}"所属项目与需求项目不一致`
      updateData.project_id = task.project_id
      needsUpdate = true
    } else if (!props.projectId && task.project_id) {
      // 任务有项目ID但需求没有，提示是否更新需求
      updateData.project_id = task.project_id
      needsUpdate = true
    }
  }
  
  // 验证版本ID是否一致（只有当任务有版本ID时才验证）
  const taskVersionId = (task as any).version_id
  if (taskVersionId) {
    if (props.versionIds && props.versionIds.length > 0) {
      // 需求有关联版本，检查是否一致
      if (!props.versionIds.includes(taskVersionId)) {
        if (!message) {
          message = `任务"${task.title}"关联的版本与需求版本不一致`
        } else {
          message += '，且版本不一致'
        }
        updateData.version_ids = [taskVersionId]
        needsUpdate = true
      }
    } else {
      // 任务有版本ID但需求没有，提示是否更新需求
      if (!message) {
        message = `任务"${task.title}"关联了版本，但需求未关联版本`
      }
      updateData.version_ids = [taskVersionId]
      needsUpdate = true
    }
  }
  
  if (needsUpdate) {
    return {
      valid: false,
      message,
      needsUpdateRequirement: true,
      updateData
    }
  }
  
  return { valid: true }
}

// 处理任务选择
const handleTaskSelected = async (tasks: Task[]) => {
  if (!tasks.length || !props.requirementId) return

  try {
    // 先验证所有任务是否符合关联条件
    const validationResults: Array<{ 
      task: Task
      valid: boolean
      message?: string
      needsUpdateRequirement?: boolean
      updateData?: { project_id?: string; version_ids?: string[] }
    }> = []
    
    for (const task of tasks) {
      // 获取任务详情以确保有完整的项目ID和版本ID信息
      let taskDetail: Task = task
      try {
        const taskResponse = await getTask(task.id)
        // 处理响应格式：可能是 { data: { success: true, data: {...} } } 或 { data: {...} }
        if (taskResponse?.data) {
          if (taskResponse.data.success && taskResponse.data.data) {
            taskDetail = taskResponse.data.data as Task
          } else if (!taskResponse.data.success) {
            // 如果不是标准格式，直接使用 data
            taskDetail = taskResponse.data as Task
          }
        }
      } catch (error) {
        console.warn(`获取任务 ${task.id} 详情失败，使用基础信息:`, error)
      }
      
      const validation = await validateTaskForAssociation(taskDetail)
      validationResults.push({ 
        task: taskDetail, 
        valid: validation.valid, 
        message: validation.message,
        needsUpdateRequirement: validation.needsUpdateRequirement,
        updateData: validation.updateData
      })
    }
    
    // 检查是否有不符合条件的任务
    const invalidTasks = validationResults.filter(r => !r.valid)
    if (invalidTasks.length > 0) {
      // 检查是否有需要更新需求的任务
      const taskNeedsUpdate = invalidTasks.find(r => r.needsUpdateRequirement && r.updateData)
      
      if (taskNeedsUpdate && taskNeedsUpdate.updateData) {
        // 显示对话框询问是否更新需求的项目和版本
        const updateInfo: string[] = []
        if (taskNeedsUpdate.updateData.project_id) {
          updateInfo.push('项目')
        }
        if (taskNeedsUpdate.updateData.version_ids && taskNeedsUpdate.updateData.version_ids.length > 0) {
          updateInfo.push('版本')
        }
        
        try {
          await ElMessageBox.confirm(
            `${taskNeedsUpdate.message || '任务项目或版本与需求不一致'}。是否更新需求的${updateInfo.join('和')}信息以匹配任务？`,
            '更新需求信息',
            {
              confirmButtonText: '更新',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
          
          // 用户确认，触发更新需求的事件
          emit('update-requirement', taskNeedsUpdate.updateData)
          
          // 等待一下，让需求更新完成，然后继续关联
          await new Promise(resolve => setTimeout(resolve, 500))
          
          // 继续关联流程（此时需求的项目和版本应该已经更新）
        } catch (error: any) {
          // 用户取消
          if (error !== 'cancel') {
            ElMessage.error('更新需求信息失败')
          }
          return
        }
      } else {
        // 其他错误，直接显示
        ElMessage.error(invalidTasks[0].message || '任务不符合关联条件')
        return
      }
    }
    
    // 先更新任务的项目ID和版本ID（如果任务没有这些信息，且项目/版本与需求不一致）
    const { taskAPI } = await import('@/api/tasks')
    for (const result of validationResults) {
      const task = result.task
      const updates: any = {}
      let needsUpdate = false
      
      // 检查任务的项目ID是否与需求一致
      const projectMatches = !props.projectId || !task.project_id || task.project_id === props.projectId
      
      // 检查任务的版本ID是否与需求一致
      const taskVersionId = (task as any).version_id
      const versionMatches = !props.versionIds || props.versionIds.length === 0 || !taskVersionId || 
                             (taskVersionId && props.versionIds.includes(taskVersionId))
      
      // 如果项目或版本不一致，且任务没有对应信息，才需要更新
      if (!projectMatches && props.projectId && !task.project_id) {
        updates.project_id = props.projectId
        needsUpdate = true
      }
      
      // 如果版本不一致，且任务没有版本ID，才需要更新
      if (!versionMatches && props.versionIds && props.versionIds.length > 0 && !taskVersionId) {
        updates.version_id = props.versionIds[0]
        needsUpdate = true
      }
      
      // 更新任务信息（只有在需要时才更新）
      if (needsUpdate) {
        try {
          await taskAPI.updateTask(task.id, updates)
        } catch (error) {
          // 继续执行，不影响关联操作
        }
      }
    }
    
    // 如果有版本ID，通过版本关联任务
    if (props.versionIds && props.versionIds.length > 0) {
      let successCount = 0
      let alreadyAssociatedCount = 0
      const errors: string[] = []
      
      const associatePromises = validationResults.map(result =>
        Promise.all(
          props.versionIds!.map(async (versionId) => {
            try {
              await versionAPI.addTaskToVersion(versionId, {
                task_id: result.task.id,
                requirement_id: props.requirementId,
                relation_type: RelationType.INCLUDED
              }, { showError: false })
              successCount++
              return { success: true }
            } catch (error: any) {
              // 提取错误消息
              let errorMessage = ''
              if (error?.response?.data?.message) {
                errorMessage = error.response.data.message
              } else if (error?.message) {
                errorMessage = error.message
              } else {
                errorMessage = '关联失败'
              }
              
              // 检查是否是"已关联"的错误
              if (errorMessage.toLowerCase().includes('already associated') || 
                  errorMessage.includes('已经关联') || 
                  errorMessage.includes('已关联') ||
                  errorMessage.includes('无需重复')) {
                alreadyAssociatedCount++
                // 不显示错误消息，因为会在后面统一显示中文提示
                return { success: false, alreadyAssociated: true }
              } else {
                errors.push(errorMessage)
                console.error(`关联任务 ${result.task.id} 到版本 ${versionId} 失败:`, error)
                return { success: false, alreadyAssociated: false }
              }
            }
          })
        )
      )
      
      await Promise.all(associatePromises)
      
      // 无论版本关联成功与否，都要关联到需求
      // 对于已经关联到版本的任务，只需要更新需求关联即可
      const taskIds = validationResults.map(r => r.task.id)
      const { taskAPI } = await import('@/api/tasks')
      
      // 直接更新任务的 requirement_id，这样可以确保关联到需求，即使版本关联失败
      try {
        await Promise.all(
          taskIds.map(async (taskId) => {
            try {
              await taskAPI.updateTask(taskId, { requirement_id: props.requirementId })
            } catch (error) {
              console.warn(`更新任务 ${taskId} 的需求关联失败:`, error)
            }
          })
        )
      } catch (error) {
        console.warn('批量更新任务需求关联失败:', error)
      }
      
      // 根据结果显示不同的提示
      if (errors.length > 0) {
        ElMessage.warning(`任务已关联到需求，但部分版本关联失败: ${errors[0]}`)
      } else if (alreadyAssociatedCount > 0 && successCount === 0) {
        // 所有任务都已关联到版本，但已更新需求关联
        ElMessage.success('任务已关联到需求')
      } else if (successCount > 0 && alreadyAssociatedCount > 0) {
        ElMessage.success(`部分任务已关联到版本，所有任务已关联到需求`)
      } else if (successCount > 0) {
        ElMessage.success('任务关联成功')
      } else {
        // 即使版本关联都失败，只要需求关联成功也算成功
        ElMessage.success('任务已关联到需求')
      }
    } else {
      // 如果没有版本ID，直接关联到需求
      const { taskAPI } = await import('@/api/tasks')
      const taskIds = validationResults.map(r => r.task.id)
      
      try {
        await Promise.all(
          taskIds.map(async (taskId) => {
            try {
              await taskAPI.updateTask(taskId, { requirement_id: props.requirementId })
            } catch (error) {
              console.warn(`更新任务 ${taskId} 的需求关联失败:`, error)
            }
          })
        )
        ElMessage.success('任务关联成功')
      } catch (error) {
        ElMessage.error('任务关联失败')
        return
      }
    }
    
    await loadRelatedTasks()
    emit('task-updated')
  } catch (error) {
    console.error('关联任务失败:', error)
    ElMessage.error('关联任务失败')
  }
}

// 移除任务关联
const handleRemoveTask = async (task: Task) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除任务"${task.title}"的关联吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (props.versionIds && props.versionIds.length > 0) {
      const removePromises = props.versionIds.map(versionId =>
        versionAPI.removeTaskFromVersion(versionId, task.id).catch(error => {
          console.error(`从版本 ${versionId} 移除任务失败:`, error)
          return null
        })
      )
      await Promise.all(removePromises)
    }

    ElMessage.success('任务关联已移除')
    await loadRelatedTasks()
    emit('task-updated')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('移除任务关联失败:', error)
      ElMessage.error('移除任务关联失败')
    }
  }
}

// 查看任务
const handleViewTask = (taskId: string) => {
  window.open(`/tasks/${taskId}`, '_blank')
}

// 添加缺陷
const handleAddDefect = () => {
  defectSelectorVisible.value = true
}

// 验证缺陷是否符合关联条件（允许项目/版本为空，但如果存在则需要一致）
const validateDefectForAssociation = async (defect: Defect): Promise<{ 
  valid: boolean
  message?: string
  needsUpdateRequirement?: boolean
  updateData?: { project_id?: string; version_ids?: string[] }
}> => {
  const updateData: { project_id?: string; version_ids?: string[] } = {}
  let needsUpdate = false
  let message = ''
  
  // 验证项目ID是否一致（只有当缺陷有项目ID时才验证）
  if (defect.project_id) {
    if (props.projectId && defect.project_id !== props.projectId) {
      // 不一致，提示并询问是否更新需求的项目
      message = `缺陷"${defect.title}"所属项目与需求项目不一致`
      updateData.project_id = defect.project_id
      needsUpdate = true
    } else if (!props.projectId && defect.project_id) {
      // 缺陷有项目ID但需求没有，提示是否更新需求
      updateData.project_id = defect.project_id
      needsUpdate = true
    }
  }
  
  // 验证版本ID是否一致（只有当缺陷有版本ID时才验证）
  if (defect.version_id) {
    if (props.versionIds && props.versionIds.length > 0) {
      // 需求有关联版本，检查是否一致
      if (!props.versionIds.includes(defect.version_id)) {
        if (!message) {
          message = `缺陷"${defect.title}"关联的版本与需求版本不一致`
        } else {
          message += '，且版本不一致'
        }
        updateData.version_ids = [defect.version_id]
        needsUpdate = true
      }
    } else {
      // 缺陷有版本ID但需求没有，提示是否更新需求
      if (!message) {
        message = `缺陷"${defect.title}"关联了版本，但需求未关联版本`
      }
      updateData.version_ids = [defect.version_id]
      needsUpdate = true
    }
  }
  
  if (needsUpdate) {
    return {
      valid: false,
      message,
      needsUpdateRequirement: true,
      updateData
    }
  }
  
  return { valid: true }
}

// 处理缺陷选择
const handleDefectSelected = async (defects: Defect[]) => {
  if (!defects.length || !props.requirementId) return

  try {
    // 先验证所有缺陷是否符合关联条件
    const validationResults: Array<{ 
      defect: Defect
      valid: boolean
      message?: string
      needsUpdateRequirement?: boolean
      updateData?: { project_id?: string; version_ids?: string[] }
    }> = []
    
    for (const defect of defects) {
      // 获取缺陷详情以确保有完整的项目ID和版本ID信息
      let defectDetail: Defect = defect
      try {
        const defectResponse = await getDefectById(defect.id)
        if (defectResponse?.success && defectResponse?.data) {
          defectDetail = defectResponse.data
        }
      } catch (error) {
        console.warn(`获取缺陷 ${defect.id} 详情失败，使用基础信息:`, error)
      }
      
      const validation = await validateDefectForAssociation(defectDetail)
      validationResults.push({ defect: defectDetail, valid: validation.valid, message: validation.message })
    }
    
    // 检查是否有不符合条件的缺陷
    const invalidDefects = validationResults.filter(r => !r.valid)
    if (invalidDefects.length > 0) {
      // 显示第一个不符合条件的缺陷的错误信息
      ElMessage.error(invalidDefects[0].message || '缺陷不符合关联条件')
      return
    }
    
    // 先更新缺陷的项目ID和版本ID（如果缺陷没有这些信息，且项目/版本与需求不一致）
    const { updateDefect } = await import('@/api/defect')
    for (const result of validationResults) {
      const defect = result.defect
      
      // 检查缺陷的项目ID是否与需求一致
      const projectMatches = !props.projectId || !defect.project_id || defect.project_id === props.projectId
      
      // 如果项目不一致，且缺陷没有项目ID，才需要更新
      // 注意：缺陷的版本关联通过版本API处理，不在这里更新
      if (!projectMatches && props.projectId && !defect.project_id) {
        try {
          await updateDefect(defect.id, { project_id: props.projectId })
        } catch (error) {
          console.warn(`更新缺陷 ${defect.id} 的项目信息失败:`, error)
          // 继续执行，不影响关联操作
        }
      }
    }
    
    // 如果有版本ID，通过版本关联缺陷（同时关联版本）
    if (props.versionIds && props.versionIds.length > 0) {
      let successCount = 0
      let alreadyAssociatedCount = 0
      const errors: string[] = []
      
      // 先通过版本关联缺陷
      const associatePromises = props.versionIds.map(versionId =>
        Promise.all(
          validationResults.map(async (result) => {
            try {
              await versionAPI.addDefectAssociation(versionId, result.defect.id, { showError: false })
              successCount++
              return { success: true }
            } catch (error: any) {
              // 提取错误消息
              let errorMessage = ''
              if (error?.response?.data?.message) {
                errorMessage = error.response.data.message
              } else if (error?.message) {
                errorMessage = error.message
              } else {
                errorMessage = '关联失败'
              }
              
              // 检查是否是"已关联"的错误
              if (errorMessage.toLowerCase().includes('already associated') || 
                  errorMessage.includes('已经关联') || 
                  errorMessage.includes('已关联') ||
                  errorMessage.includes('无需重复')) {
                alreadyAssociatedCount++
                // 不显示错误消息，因为会在后面统一显示中文提示
                return { success: false, alreadyAssociated: true }
              } else {
                errors.push(errorMessage)
                console.error(`关联缺陷 ${result.defect.id} 到版本 ${versionId} 失败:`, error)
                return { success: false, alreadyAssociated: false }
              }
            }
          })
        )
      )
      
      await Promise.all(associatePromises)
      
      // 无论版本关联成功与否，都要关联到需求
      // 对于已经关联到版本的缺陷，只需要更新需求关联即可
      const defectIds = validationResults.map(r => r.defect.id)
      
      try {
        const response = await batchUpdateDefectsRequirement(defectIds, props.requirementId)
        
        // 根据结果显示不同的提示
        if (response.success) {
          if (errors.length > 0) {
            ElMessage.warning(`缺陷已关联到需求，但部分版本关联失败: ${errors[0]}`)
          } else if (alreadyAssociatedCount > 0 && successCount === 0) {
            // 所有缺陷都已关联到版本，但已更新需求关联
            ElMessage.success('缺陷已关联到需求')
          } else if (successCount > 0 && alreadyAssociatedCount > 0) {
            ElMessage.success(`部分缺陷已关联到版本，所有缺陷已关联到需求`)
          } else if (successCount > 0) {
            ElMessage.success('缺陷关联成功')
          } else {
            // 即使版本关联都失败，只要需求关联成功也算成功
            ElMessage.success('缺陷已关联到需求')
          }
          await loadRelatedDefects()
          emit('defect-updated')
        } else {
          // 即使需求关联失败，如果版本关联成功，也要提示
          if (successCount > 0 || alreadyAssociatedCount > 0) {
            ElMessage.warning('缺陷已关联到版本，但关联到需求失败')
          } else {
            ElMessage.error(response.message || '缺陷关联失败')
          }
        }
      } catch (error: any) {
        console.error('关联缺陷到需求失败:', error)
        // 即使需求关联失败，如果版本关联成功，也要提示
        if (successCount > 0 || alreadyAssociatedCount > 0) {
          ElMessage.warning('缺陷已关联到版本，但关联到需求失败')
        } else {
          ElMessage.error('缺陷关联失败')
        }
      }
    } else {
      // 如果没有版本ID，只关联到需求
      const defectIds = validationResults.map(r => r.defect.id)
      const response = await batchUpdateDefectsRequirement(defectIds, props.requirementId)
      
      if (response.success) {
        ElMessage.success('缺陷关联成功')
        await loadRelatedDefects()
        emit('defect-updated')
      } else {
        ElMessage.error(response.message || '缺陷关联失败')
      }
    }
  } catch (error) {
    console.error('关联缺陷失败:', error)
    ElMessage.error('关联缺陷失败')
  }
}

// 移除缺陷关联
const handleRemoveDefect = async (defect: Defect) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除缺陷"${defect.title}"的关联吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    defectsLoading.value = true
    const response = await batchUpdateDefectsRequirement([defect.id], null)
    if (response.success) {
      ElMessage.success('移除成功')
      await loadRelatedDefects()
      emit('defect-updated')
    } else {
      ElMessage.error(response.message || '移除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('移除缺陷关联失败:', error)
      ElMessage.error('移除失败')
    }
  } finally {
    defectsLoading.value = false
  }
}

// 查看缺陷
const handleViewDefect = (defectId: string) => {
  router.push(`/defects/${defectId}`)
}

// 任务状态相关
const getTaskStatusType = (status?: string) => {
  if (!status) return 'info'
  const statusMap: Record<string, 'success' | 'info' | 'warning' | 'danger'> = {
    done: 'success',
    todo: 'info',
    in_progress: 'warning',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getTaskStatusName = (status?: string) => {
  if (!status) return '未知'
  return getTaskStateName(status) || status
}

const getTaskPriorityType = (priority?: string) => {
  if (!priority) return 'info'
  const priorityMap: Record<string, 'success' | 'info' | 'warning' | 'danger'> = {
    low: 'info',
    medium: 'success',
    high: 'warning',
    urgent: 'danger'
  }
  return priorityMap[priority] || 'info'
}

const getTaskPriorityName = (priority?: string) => {
  if (!priority) return '未知'
  const priorityMap: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急'
  }
  return priorityMap[priority] || priority
}

// 缺陷状态相关
const getDefectStatusType = (status?: string) => {
  if (!status) return 'info'
  const color = getDefectStateColor(status)
  if (color.includes('green') || color.includes('success')) return 'success'
  if (color.includes('red') || color.includes('danger')) return 'danger'
  if (color.includes('orange') || color.includes('warning')) return 'warning'
  return 'info'
}

const getDefectStatusName = (status?: string) => {
  if (!status) return '未知'
  return getDefectStateName(status) || status
}

const getDefectSeverityType = (severity?: string) => {
  if (!severity) return 'info'
  const code = severity.toLowerCase()
  if (code === 'critical' || code === 'urgent' || code === 'blocker') return 'danger'
  if (code === 'important' || code === 'major') return 'warning'
  return 'info'
}

const getDefectSeverityName = (severity?: string) => {
  if (!severity) return '未知'
  return getSeverityNameFromOptions(severity) || severity
}

const getDefectPriorityType = (priority?: string) => {
  if (!priority) return 'info'
  const code = priority.toLowerCase()
  if (code === 'critical' || code === 'urgent' || code === 'blocker') return 'danger'
  if (code === 'high') return 'warning'
  if (code === 'medium') return 'success'
  return 'info'
}

const getDefectPriorityName = (priority?: string) => {
  if (!priority) return '未知'
  return getPriorityNameFromOptions(priority) || priority
}

watch(() => props.requirementId, (newId) => {
  if (newId) {
    if (activeSubTab.value === 'tasks') {
      loadRelatedTasks()
    } else {
      loadRelatedDefects()
    }
  } else {
    relatedTasks.value = []
    relatedDefects.value = []
  }
}, { immediate: true })

watch(() => activeSubTab.value, (tab) => {
  if (tab === 'tasks' && props.requirementId) {
    loadRelatedTasks()
  } else if (tab === 'defects' && props.requirementId) {
    loadRelatedDefects()
  }
})

onMounted(async () => {
  await Promise.all([
    loadTaskStates(),
    loadDefectStates(),
    loadDefectOptions()
  ])
  if (props.requirementId) {
    if (activeSubTab.value === 'tasks') {
      loadRelatedTasks()
    } else {
      loadRelatedDefects()
    }
  }
})

// 暴露刷新方法供父组件调用（必须在函数声明之后）
defineExpose({
  refreshTasks: loadRelatedTasks,
  refreshDefects: loadRelatedDefects
})
</script>

<style scoped lang="scss">
.requirement-associations-tab {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.association-sub-tabs {
  :deep(.el-tabs__header) {
    margin: 0;
  }

  :deep(.el-tabs__content) {
    padding: 0;
  }
}

.sub-tab-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.header-info {
  .item-count {
    font-size: 15px;
    font-weight: 600;
    color: #303133;
  }
}

.header-actions {
  display: flex;
  gap: 8px;
}

.items-list {
  min-height: 300px;
}
</style>

